import React from 'react'
import {connect} from 'react-redux'
import {messages} from 'share/common';
import { Button, message, Popconfirm, Affix, Popover } from 'antd';
import ResizeTable from 'components/resize-table'
import menuRoute from 'routes/menuRoute'
import SlideFrame from "components/slide-frame";
import 'styles/setting/wait-for-billing/invoice-status-query.scss';
import AsyncExport from "components/template/async-export/async-export";
import ImportModal from "components/template/import-modal-ie/import-modal";
import SearchArea from 'components/search-area';
import ObjectRule from "containers/financial-account/interface-definition/object-rule";
import interfaceService from "containers/financial-account/interface-definition/interface-service";

class objectMapping extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      infoData: {},
      columns: [
        {title: messages('financial-account.key109')/*会计科目编码*/,dataIndex: 'accountingCode'},
        {title: messages('financial-account.key110')/*会计科目名称*/,dataIndex: 'accountingName'},
        {title: messages('common.operation')/*操作*/, width: 110, dataIndex: 'operation', render: (value,record) => {
            return <span>
              <a onClick={e => this.handleEdit(e,record)}>{messages('common.edit')/*编辑*/}</a>
              <span className="ant-divider"/>
              <Popconfirm onConfirm={() => this.handleDelete(record)}
                          title={messages('financial-account.key150')/*是否删除当前科目映射*/}>
                <a>{messages('common.delete')/*删除*/}</a>
              </Popconfirm>
            </span>;}}
      ],
      searchForm: [
        {
          type: 'list',
          id: 'accountCode',
          listType: 'select_object',
          label: messages('financial-account.key202')/*会计科目编码/名称*/,
          labelKey: 'accountName',
          valueKey: 'accountCode',
          single: true,
          listExtraParams: {
            setOfBooksId: props.settingMate.setOfBooksId
          }
        }
      ],
      searchParams: {},
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      page: 0,
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      selectIds: [],
      showSlideFrame: false,
      editRecord: {},
      title: ''
    }
  }

  componentDidMount() {
    this.setState({infoData: this.props.settingMate},() => {
      const { infoData, columns, searchForm } = this.state;
      const { tenant } = this.props;
      infoData.sceneElementSimpleDTOList && infoData.sceneElementSimpleDTOList.map((item,index) => {
        columns.splice(2 + index, 0, {title: item.elementName, dataIndex: `arg${index}`, render: (value,record) => {
            let {refElementTargetCode, refElementTargetValue} = record.accountingSceneDetailList[index];
            return <Popover content={refElementTargetCode ? `${refElementTargetCode} - ${refElementTargetValue}` : refElementTargetValue} placement={'topLeft'}>{refElementTargetCode ? `${refElementTargetCode} - ${refElementTargetValue}` :refElementTargetValue}</Popover>
          }
        });
        let tempObj = {
          type: item.type ? 'select' : 'input',
          id: `arg${index}`,
          label: item.elementName
        };
        if (tempObj.type === 'select') {
          tempObj = Object.assign(tempObj,{
            getUrl: `/api/open/ledger/element/value/group?tenantId=${tenant.id}&setOfBooksId=${infoData.setOfBooksId}&types=${item.type}`,
            options: [], labelKey: 'showName', valueKey: 'code', method: 'get', listKey: 'data.0.ledElementValueDTOList'
          })
        }
        searchForm.splice(1 + index, 0, tempObj);
      });
      this.setState({ columns, searchForm },() => {
        this.getList();
      });
    });
  }

  onSelectChange = (selectedRowKeys) => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    let { selectIds } = this.state;
    if(selected){
      changeRows.map(item => {
        selectIds.filter(ids => ids === item.id).length === 0 && selectIds.push(item.id);
      })
    } else {
      changeRows.map(item => {
        selectIds.map((ids,index) => {
          if(item.id === ids){
            selectIds[index] = undefined;
          }
        });
      });
      selectIds = selectIds.filter(item => !!item);
    }
    this.setState({selectIds});
  };

  onSelectItem = (record, selected) => {
    let { selectIds } = this.state;
    if(selected){
      selectIds.filter(item => item === record.id).length === 0 && selectIds.push(record.id);
    } else {
      selectIds.map((item,index) => {
        item === record.id && (selectIds[index] = undefined);
      });
      selectIds = selectIds.filter(item => !!item);
    }
    this.setState({selectIds});
  };

  getList = () => {
    const { infoData, page, searchParams } = this.state;
    let temp = Object.assign(searchParams, { page, sceneMappingGroupId: infoData.id });
    this.setState({loading: true});
    interfaceService.getObjectList(temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false});
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  search = result => {
    const { infoData } = this.state;
    let searchParams = {};
    let accountingElements = [];
    infoData.sceneElementSimpleDTOList && infoData.sceneElementSimpleDTOList.map((item, index) => {
      result[`arg${index}`] && (accountingElements.push({ elementCode: item.elementCode, elementTargetCode: result[`arg${index}`] }));
    });
    searchParams.accountingElements = accountingElements;
    result.accountCode && (searchParams.accountCode = result.accountCode[0]);
    this.setState({ searchParams }, () => {
      this.getList();
    })
  };

  clear = () => {
    this.setState({ searchParams: {} }, () => this.getList());
  };

  handleAdd = () => {
    this.setState({
      title: messages('financial-account.key112')/*新建匹配科目*/,
      editRecord: {}
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  handleDelete = (record) => {
    const { selectIds } = this.state;
    if(!record && selectIds.length === 0){
      message.error(messages('financial-account.key148')/*请选择再进行删除*/);
      return -1;
    }
    let list = record ? [record.id] : selectIds;
    let temp = {
      accountIdList: list
    };
    interfaceService.deleteObject(temp).then(() => {
      message.success(messages('common.operate.success')/*操作成功*/);
      this.setState({ page: 0 }, () => {
        this.getList();
      });
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  handleEdit = (e,record) => {
    e.stopPropagation();
    this.setState({
      title: messages('financial-account.key113')/*编辑匹配科目*/,
      editRecord: record
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  isRefresh = (isRefresh) => {
    this.setState({showSlideFrame: false});
    isRefresh === true && this.getList();
  };

  goBack = () => {
    this.context.router.push(menuRoute.getRouteItem('setting-mate').url.replace(':tab','accounting-background-definition'));
  };

  render(){
    const { infoData, columns, data, loading, pagination, rowSelection, showSlideFrame, title, editRecord, searchForm,
      searchParams } = this.state;
    const { loginUser, language } = this.props;
    let templates = [{
      downloadName: messages('financial-account.key162')/*会计科目映射模板*/,
      templateName: messages('financial-account.key162')/*会计科目映射模板*/,
      downloadUrl: `/ledger/api/download/template`,
      downloading: "mapLoading",
      downloadMethod: 'post',
      params: {
        templateType: 'ACCOUNTING_MAPPING',
        language: language.code,
        otherDownLoadMsg: {
          sceneMappingGroupId: infoData.id
        }
      }
    }];
    return(
      <div className="invoice-status">
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
        />
        <div style={{margin:'10px 0px'}} className="buttons">
          <Button type="primary" onClick={this.handleAdd}>{messages('common.create')}</Button>
          <Button onClick={() => this.handleDelete()}>{messages('common.delete')/*删除*/}</Button>
          <ImportModal
            buttonName={messages('financial-account.key163')/*导入数据*/}
            templates={templates}
            hasErrInfo={false}
            uploadUrl={`/ledger/api/ledScene/accountingMap/config/import?sceneMappingGroupId=${infoData.id}&language=${language.code}`}
            onCancel={() => {
              this.setState({page: 0}, () => {
                this.getList();
              })
            }}
          />
          <div style={{display:'inline-block'}}>
            <AsyncExport
              title={messages('financial-account.key164')/*导出数据*/}
              style={{ display: 'inline-block' }}
              params={{
                tenantId: loginUser.tenantId,
                setOfBooksId: infoData.setOfBooksId,
                operatorOid: loginUser.userOID,
                accountCode: searchParams.accountCode,
                accountingElements: searchParams.accountingElements,
                implName: 'accountMappingGroupDownloadImpl',
                isAsync: true,
                otherDownloadMsg: {
                  sceneMappingGroupId: infoData.id,
                  language: language.code,
                  withConfigValue: true
                }
              }}
            />
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey={'id'}
          rowSelection={rowSelection}
          pagination={pagination}
          bordered/>
        <SlideFrame show={showSlideFrame}
                    title={title}
                    params={{
                      showSlideFrame,
                      editRecord
                    }}
                    content={ObjectRule}
                    onClose={(isRefresh) => this.isRefresh(isRefresh)}
                    afterClose={(isRefresh) => this.isRefresh(isRefresh)}/>
        <Affix offsetBottom={0} className="bottom-bar">
          <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

objectMapping.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {
    settingMate: state.financialAccount.settingMate,
    language: state.main.language,
    loginUser: state.login.loginUser,
    tenant: state.login.tenant
  }
}

export default connect(mapStateToProps)(objectMapping);
